package com.gaga.console.core.controller.sys;


import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gaga.common.constant.BvConstants;
import com.gaga.common.enums.DelFlag;
import com.gaga.common.enums.SingleDoubleModelType;
import com.gaga.common.path.ApiPath;
import com.gaga.common.result.Result;
import com.gaga.console.base.controller.BaseController;
import com.gaga.console.base.entity.PageParams;
import com.gaga.console.base.mybatisplus.LambdaQueryWrapperExt;
import com.gaga.console.core.entity.BvScriptCategory;
import com.gaga.console.core.entity.SysConfig;
import com.gaga.console.core.entity.dto.ConfigDto;
import com.gaga.console.core.service.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户信息表 前端控制器
 *
 * @author liujia
 * @since 2025-03-27
 */
@RestController
@RequestMapping(ApiPath.ROOT + "/sys/config")
@Slf4j
public class SysConfigController extends BaseController {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private BvConfigService bvConfigService;

    @Autowired
    private BvScriptCategoryService bvScriptCategoryService;

    @Autowired
    private AssistantService assistantService;

    @Autowired
    private BvAudioPlayService bvAudioPlayService;

    /**
     * 获取列表
     */
    @ApiOperation(value = "查询list")
    @PostMapping("/list")
    public Result list(@RequestBody PageParams<SysConfig> data) {

        LambdaQueryWrapperExt<SysConfig> wraps = new LambdaQueryWrapperExt<>();
        wraps.eq(SysConfig::getDelFlag, DelFlag.OK.getCode());
        data.buildSpecWrap(wraps);

        IPage<SysConfig> page = sysConfigService.page(data.buildPage(), wraps);

        return Result.ok(data.buildTableResult(page));
    }

    /**
     * 根据详细信息
     */
    @ApiOperation(value = "获取单个记录")
    @GetMapping(value = "/{id}")
    public Result getEntity(@PathVariable Long id) {
        return Result.ok(sysConfigService.getById(id));
    }

    /**
     * 根据详细信息
     */
    @ApiOperation(value = "根据configKey获取单个记录")
    @GetMapping(value = "/configKey/{configKey:.+}")
    public Result getByConfigKey(@PathVariable String configKey) {
        return Result.ok(sysConfigService.getByConfigKey(configKey));
    }


    /**
     * 保存
     */
    @ApiOperation(value = "保存记录")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysConfig entity) {
        SysConfig sysConfig = sysConfigService.getById(entity.getId());
        if (sysConfig.getConfigKey().equals(BvConstants.SINGLE_DOUBLE_MODEL)) {
            ConfigDto config = bvConfigService.getConfig();

            List<String> modelList = Arrays.asList(
                    config.getModelSetting().getAnchor(),
                    config.getModelSetting().getAssistant()
            );

            // 解密模型
            bvAudioPlayService.decryptModel(modelList);

            SysConfig portConfig = sysConfigService.getByConfigKey(BvConstants.MODEL_RUN_PORT);
            if (portConfig == null) {
                return Result.ok();
            }

            if (!sysConfig.getConfigValue().equals(entity.getConfigValue())) {
                if (SingleDoubleModelType.SINGLE.getCode().equals(entity.getConfigValue())) {
                    assistantService.shutDownModel("9875");
                    assistantService.shutDownModel("9881");

                    SysConfig updateConfig = new SysConfig();
                    updateConfig.setId(portConfig.getId());
                    updateConfig.setConfigValue("9876");
                    sysConfigService.saveOrUpdate(updateConfig);

                    if (!assistantService.isModelRunning("9876")) {
                        String modelPath9876 = sysConfigService.getAbsolutePathByKey(BvConstants.MODEL_BAT_PATH_9876);
                        assistantService.exec(modelPath9876, "模型", false, true);
                    }

                } else if (SingleDoubleModelType.DOUBLE.getCode().equals(entity.getConfigValue())) {
                    assistantService.shutDownModel("9881");

                    SysConfig updateConfig = new SysConfig();
                    updateConfig.setId(portConfig.getId());
                    updateConfig.setConfigValue("9875,9876");
                    sysConfigService.saveOrUpdate(updateConfig);

                    if (!assistantService.isModelRunning("9875")) {
                        String modelPath9875 = sysConfigService.getAbsolutePathByKey(BvConstants.MODEL_BAT_PATH_9875);
                        assistantService.exec(modelPath9875, "模型", false, true);
                    }

                    if (!assistantService.isModelRunning("9876")) {
                        String modelPath9876 = sysConfigService.getAbsolutePathByKey(BvConstants.MODEL_BAT_PATH_9876);
                        assistantService.exec(modelPath9876, "模型", false, true);
                    }

                } else if (SingleDoubleModelType.COMPATIBLE.getCode().equals(entity.getConfigValue())) {
                    assistantService.shutDownModel("9875");
                    assistantService.shutDownModel("9876");

                    SysConfig updateConfig = new SysConfig();
                    updateConfig.setId(portConfig.getId());
                    updateConfig.setConfigValue("9881");
                    sysConfigService.saveOrUpdate(updateConfig);

                    if (!assistantService.isModelRunning("9881")) {
                        String modelPath9881 = sysConfigService.getAbsolutePathByKey(BvConstants.MODEL_BAT_PATH_9881);
                        assistantService.exec(modelPath9881, "模型", false, true);
                    }
                }
                try {
                    Thread.sleep(15000);
                } catch (InterruptedException e) {
                    log.error("线程休眠异常", e);
                }
            }
        }
        return toAjaxBoolean(sysConfigService.saveOrUpdate(entity));
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除记录")
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable Long[] ids) {

        if (ArrayUtil.isEmpty(ids)) {
            return toAjaxBoolean(false);
        }

        List<SysConfig> removeEntityList = Arrays.stream(ids)
                .map(id -> {
                    SysConfig entity = new SysConfig().setId(id);
                    entity.setDelFlag(DelFlag.DELETED.getCode());
                    entity.setDeleteTime(new Date());
                    return entity;
                }).collect(Collectors.toList());

        return toAjaxBoolean(sysConfigService.updateBatchById(removeEntityList));
    }

    /**
     * 删除
     */
    @ApiOperation(value = "获取播放日志文件位置及音频文件位置")
    @GetMapping("/getPosition")
    public Result getPosition() {

        String playLogFilePath = sysConfigService.getAbsolutePathByKey(BvConstants.PLAY_LOG_FILE_PATH);
        String generateAudioPath = sysConfigService.getAbsolutePathByKey(BvConstants.GENERATE_AUDIO_PATH);

        Long categoryId = bvConfigService.getConfig().getFileDirectory().getCategoryId();
        BvScriptCategory category = bvScriptCategoryService.getById(categoryId);
        if (category != null && StringUtils.isNotBlank(category.getScriptCategoryName())) {
            playLogFilePath = playLogFilePath + "/" + category.getScriptCategoryName();
        }

        if (category != null && StringUtils.isNotBlank(category.getScriptCategoryName())) {
            generateAudioPath = generateAudioPath + "/" + category.getScriptCategoryName();
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("playLogFilePath", playLogFilePath);
        jsonObject.put("generateAudioPath", generateAudioPath);

        return Result.ok(jsonObject);
    }

}
